#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PATH "."
#define FILENAME "fifo"

//这个宏是我们以后代码出错直接用这个宏，不用一行一行输出错误信息了
#define ERR_EXIT(m) \
do \
{ \
    perror(m); \
    exit(EXIT_FAILURE); \
} while (0)



class NameFifo
{
public:
    NameFifo(const std::string &path, const std::string &name)
        : _path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        // 创建管道文件
        umask(0);
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            ERR_EXIT("create");
        }
        std::cout << "creat sucess! " << std::endl;
    }

    ~NameFifo()
    {
        // 关闭管道文件
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "close sucess! " << std::endl;
        }
        else
        {
            ERR_EXIT("close");
        }
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
};

class FileOper
{
public:
    FileOper(const std::string &path, const std::string &name)
        : _path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    void OpenForRead()
    {
        // 让server文件读取管道内容，就是进行文件操作
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
            return;
        }
        std::cout << "open fifo sucess!" << std::endl;
    }
    void OpenForWrite()
    {
        // 打开管道文件，然后再读就行了
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
            return;
        }
        std::cout << "open fifo sucess!" << std::endl;
    }
    void Write()
    {
        // write
        std::string message;
        int cnt = 1;
        pid_t pid = getpid();
        while (true)
        {
            std::cout << "Please Entter# ";
            getline(std::cin, message);
            message += (", message number" + std::to_string(cnt++) + ",[ " + std::to_string(pid) + " ]");
            write(_fd, message.c_str(), message.size());
        }
    }
    void Read()
    {
        // read
        while (true)
        {
            char buffer[1024];
            int num = read(_fd, buffer, sizeof(buffer) - 1);
            if (num > 0)
            {
                buffer[num] = 0;
                std::cout << "client say# " << buffer << std::endl;
            }
            else if (num == 0)
            {
                std::cout << "client quit! me too!" << std::endl;
                break;
            }
            else
            {
                ERR_EXIT("read");
            }
        }
    }
    void Close()
    {
        if (_fd > 0)
        {
            close(_fd);
        }
    }
    ~FileOper()
    {
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};
